package basics;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


public class DBManager {

	private static final String DB_DRIVER = "org.hsqldb.jdbcDriver";
	private static final String DB_URL = "jdbc:hsqldb:file:sql/testdb1;shutdown=true;hsqldb.default_table_type=cached";
	private static final String DB_USERNAME = "sa";
	private static final String DB_PASSWORD = "";
	
	public static Connection connect() {
		Connection c = null;
		try {
			Class.forName(DB_DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.exit(0);
		}
		try {
			c = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
			c.setAutoCommit(false);
		} catch (SQLException e) {
			e.printStackTrace();
			System.exit(0);
		}	
		return c;
	}
	
	public static void Log(String Tag,String Mensaje)
	{
		try 
		{
			Mensaje = Mensaje.replace("'","");
			String sql = String.format("INSERT INTO Log (Tag, Mensaje) VALUES ('%s','%s')", Tag,Mensaje);
			//String sql = " ('" + Tag + "', '" + Mensaje + "')";

			Connection c = connect();
			Statement s = c.createStatement();
			s.execute(sql);
			c.commit();
			c.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void shutdown() throws Exception {
		Connection c = connect();
		Statement s = c.createStatement();
		s.execute("SHUTDOWN");
		c.close();
	}

	public static void Error(Exception ex) {
		try {
			String sql = "INSERT INTO Errores (Message, StackTrace) VALUES ('" + ex.getMessage() + "', '" + ex.getCause() + "')";

			Connection c = connect();
			Statement s = c.createStatement();
			s.execute(sql);
			c.commit();
			c.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	
}
